import { onMounted, nextTick, ref, reactive, watch, watchEffect } from 'vue'
import Config from './mapConfig'
import Scalarlayer from './scalarLayer'
import ParticleLayer from './ParticleLayer'
import { queryList } from './mapQuery'
import mitt from '../../assets/js/mitt'
import * as echarts from 'echarts'
import { ElLoading } from 'element-plus'
import axios from 'axios'
import 'leaflet-arrowheads';
import arrow from '@/assets/img/arrow.png'
import 'leaflet-rotatedmarker'
import dfJson from '@/assets/json/预报堤段.json'
import hyJson from '@/assets/json/预报海域.json'
import hxJson from '@/assets/json/预报航线.json'
import yuanhong from '@/assets/img/yuanhong.png'
import * as turf from '@turf/turf'
import provider from '../../stores/provider'
import testJson from '@/assets/json/a.json'

const url = import.meta.env.VITE_backurl
const tianditu_v_nosea = import.meta.env.VITE_jiedao_nosea,
  tianditu_v = import.meta.env.VITE_jiedao
const { key } = provider
export const mapObj = {
  zoom: 10,
  currentTileLayer: null,
  currentLine: [],
  allArrow: [],
  allValue: [],
  allTxt: [],
  allQy: [],
  listValue: [],
  center: [36.094250487918594, 120.2911099335937],
}

export let layerMap = {}
export const currentFore = ref()

export const initMap = (data) => {
  Config.AllLayers = {
    surgeLayer: Scalarlayer({ //増水
      scalarColor: Config.scalarColor.surge,
      zindex: Config.layerIndex.waveIndex,
      opacity: 0.9,
      type: "surge",
      surgeTP: "",
      showLabel: false,
      magnification: 1,//画布缩放比例
    }),
    waveLayer: Scalarlayer({ //浪
      scalarColor: Config.scalarColor.wave,
      zindex: Config.layerIndex.waveIndex,
      opacity: 1.0,
      type: "wave",
      showLabel: false,
      pane: 'pngPan',
      magnification: 1,
    }),
    tideLayer: Scalarlayer({ //潮汐
      scalarColor: Config.scalarColor.tide,
      zindex: Config.layerIndex.waveIndex,
      opacity: 0.9,
      type: "tide",
      showLabel: false,
      magnification: 1,
    }),
    windLayer: Scalarlayer({ //风
      scalarColor: Config.scalarColor.wind,
      zindex: Config.layerIndex.windIndex,
      opacity: 0.8,
      type: "wind",
      showLabel: false,
      magnification: 1,
    }),
    windParticleLayer: ParticleLayer({ //风场粒子
      zindex: Config.layerIndex.windParticle,
      magnification: 1, //画布缩放比例
      color: ["rgba(255,255,255,1)"],
      velocityScale: 0.005, //步长，流动速度(尽量不变)
      globalAlpha: 0.9, //全局透明度
      particleAge: 30, //粒子生命周期
      particleMultiplier: 400, //密度
      frame_rate: 30, //刷新率
      lineWidth: 1.5, //线宽
      type: "wind",
    }),
    currentLayer: ParticleLayer({ //精细化流场粒子
      zindex: Config.layerIndex.currentParticle,
      magnification: 1, //画布缩放比例
      color: ["rgba(255,81,0,1)"],
      velocityScale: 0.08, //步长，流动速度(尽量不变)
      globalAlpha: 0.95, //全局透明度
      particleAge: 80, //粒子生命周期
      particleMultiplier: 600, //密度
      frame_rate: 20, //刷新率
      lineWidth: 1, //线宽
      type: "current",
    }),
    boundaryLineLayer1: L.tileLayer.wms("https://geomap.oceanread.com:5812/geoserver/world_boundary/wms?", {
      layers: 'world_boundary:world_vector_forWMP1',
      format: 'image/png',
      transparent: true,
      pane: 'overlayPane',
      zIndex: Config.layerIndex.boundaryLine,
    }),
    tianditu_v: L.tileLayer(tianditu_v),
    arcgis: L.tileLayer("http://39.103.180.154:1001/mapTile/tianditu_vec_source/{z}/{y}/{x}.png"),
    tianditu_v_nosea: L.tileLayer(tianditu_v_nosea, {
      pane: 'overlayPane',
      zIndex: Config.layerIndex.noSeaIndex,
    }),
  }

  let baseLayer = L.tileLayer("http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}", {
    attribution: '&copy; 高德地图',
    // maxZoom: 13,
    // minZoom: 3,
    subdomains: "1234",
    zoom: 3
  });

  let map = L.map('mapContain', {
    attributionControl: false,
    crs: L.CRS.EPSG3857,
    zoomControl: false,
    // maxZoom: 12,
    // minZoom: 3,
    zoomSnap: 0.1,
    renderer: L.canvas(),
    // dragging: false,
    // 全屏
    fullscreenControl: true,
    // maxBounds: L.latLngBounds(L.latLng(28.187638430515555, 121.80061340332033), L.latLng(27.611146975569007, 120.39985656738283)),
  }).setView(mapObj.center, mapObj.zoom)
  mapObj.map = map
  // Config.AllLayers.arcgis.addTo(mapObj.map)
  // map.addLayer(baseLayer);
  const imageURL = "http://t0.tianditu.gov.cn/img_w/wmts?" +
    "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
    "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}" +
    "&tk=01662809231e0055688595411a950716";
  L.tileLayer(imageURL, {
    attribution: "stamen"
  }).addTo(mapObj.map);

  Config.ToolLayers = L.layerGroup().addTo(mapObj.map)
  const wzCenter = [27.9911, 120.6993]

  // console.log(testJson.features[0].geometry.coordinates)
  let testPolygon = testJson.features[0].geometry.coordinates
  // 获取经度和纬度的最大值和最小值
  let maxLng = testPolygon[0][0][0],
    minLng = testPolygon[0][0][0],
    maxLat = testPolygon[0][0][1],
    minLat = testPolygon[0][0][1];
  for (let i = 0; i < testPolygon[0].length; i++) {
    let lng = testPolygon[0][i][0];
    let lat = testPolygon[0][i][1];
    if (lng > maxLng) maxLng = lng;
    if (lng < minLng) minLng = lng;
    if (lat > maxLat) maxLat = lat;
    if (lat < minLat) minLat = lat;
  }
  console.log(maxLng, minLng, maxLat, minLat)
  // 加载testJson
  // let testLayer = L.geoJSON(testJson, {
  //   style: function (feature) {
  //     return {
  //       color: "#ff0000",
  //       weight: 1,
  //       opacity: 0.7,
  //       fillOpacity: 0,
  //       zIndex: 1,
  //     };
  //   }
  // }).addTo(mapObj.map)


  initHt()

  if (key == 'ais') {
    // map.setView([27.20235058486227, 120.51932012727352], mapObj.zoom)
    // initSanAo()
    // addnoseaLayer()
    return
  }

  // 潮位站
  let t1 = L.marker([27.897596872, 120.939999680], {
    icon: L.icon({
      className: "tideStation111",
      iconUrl: './img/rbrpng.png',
      iconSize: [20, 20],
    }),
    draggable: false,
  }),
    myIcon = L.divIcon({
      html: `<div class="marker-label">T1</div>`,
      className: 'my-div-icon',
      iconSize: [35, 35],
      iconAnchor: [5, -15],
    }),
    markerTxt = L.marker([27.897596872, 120.939999680], {
      icon: myIcon,
    })
  t1.on('click', () => {
    mitt.emit('tideClick', 't1')
  })
  t1.addTo(mapObj.map)
  markerTxt.addTo(mapObj.map)

  let t2 = L.marker([27.893991983, 121.012612443], {
    icon: L.icon({
      className: "tideStation111",
      iconUrl: './img/rbrpng.png',
      iconSize: [20, 20],
    }),
    draggable: false,
  }),
    tText2 = L.divIcon({
      html: `<div class="marker-label">T2</div>`,
      className: 'my-div-icon',
      iconSize: [35, 35],
      iconAnchor: [5, -15],
    }),
    tTxt2 = L.marker([27.893991983, 121.012612443], {
      icon: tText2,
    })
  t2.on('click', () => {
    mitt.emit('tideClick', 't2')
  })
  t2.addTo(mapObj.map)
  tTxt2.addTo(mapObj.map)


  let marker1 = L.marker([27.7909444, 120.9943333], {
    icon: L.icon({
      className: "fubiao",
      iconUrl: './img/sanjiao.png',
      iconSize: [15, 15],
    }),
    draggable: false,
  }), myIcon1 = L.divIcon({
    // 霓屿
    html: `<div class="marker-label">浮标</div>`,
    className: 'fubiao_label',
    iconSize: [55, 35],
    iconAnchor: [10, -10],
  }),
    markerTxt1 = L.marker([27.7909444, 120.9943333], {
      icon: myIcon1,
    })

  marker1.on('click', () => {
    mitt.emit('fubiaoClick')
  })
  marker1.addTo(mapObj.map)
  markerTxt1.addTo(mapObj.map)

  // addArrow({
  //   lat: 27.91100246095729,
  //   lng: 120.92814856745156,
  //   angle: 0,
  // })
  // mapObj.allQy清空
  clearAllQy()

  addHyLayer()
  addDfLayer()
  addHxLayer()
  addAllTxt()


  mapObj.allQy.forEach(item => {
    item.layer.on('click', (e) => {
      mitt.emit('layerClick', item.name)
    })
  })


}

// 画一个矩形，边界为[36.3, 118.0],[31.3, 125.0]
export const initHt = () => {
  // let bounds = [[37, 118.0], [32, 125.0]]
  let bounds = [[38, 119.0], [34, 124.0]]

  let rectangle = L.rectangle(bounds, {
    color: "red",
    weight: 2,
    fillOpacity: 0,
  }).addTo(mapObj.map);
  // mapObj.map.fitBounds(bounds);
}

export const addHy = () => {

}

export const initMapElse = (data) => {
  Config.AllLayers = {
    surgeLayer: Scalarlayer({ //増水
      scalarColor: Config.scalarColor.surge,
      zindex: Config.layerIndex.waveIndex,
      opacity: 0.9,
      type: "surge",
      surgeTP: "",
      showLabel: false,
      magnification: 1,//画布缩放比例
    }),
    waveLayer: Scalarlayer({ //浪
      scalarColor: Config.scalarColor.wave,
      zindex: Config.layerIndex.waveIndex,
      opacity: 1.0,
      type: "wave",
      showLabel: false,
      pane: 'pngPan',
      magnification: 1,
    }),
    tideLayer: Scalarlayer({ //潮汐
      scalarColor: Config.scalarColor.surge,
      zindex: Config.layerIndex.waveIndex,
      opacity: 0.9,
      type: "tide",
      showLabel: false,
      magnification: 1,
    }),
    windLayer: Scalarlayer({ //风
      scalarColor: Config.scalarColor.wind,
      zindex: Config.layerIndex.windIndex,
      opacity: 0.9,
      type: "wind",
      showLabel: false,
      magnification: 1,
    }),
    currentLayer: ParticleLayer({ //精细化流场粒子
      zindex: Config.layerIndex.currentParticle,
      magnification: 1, //画布缩放比例
      color: ["rgba(255,81,0,1)"],
      velocityScale: 0.08, //步长，流动速度(尽量不变)
      globalAlpha: 0.95, //全局透明度
      particleAge: 80, //粒子生命周期
      particleMultiplier: 1200, //密度
      frame_rate: 20, //刷新率
      lineWidth: 1, //线宽
      type: "rcurrent",
    }),
    tianditu_v: L.tileLayer(
      tianditu_v
    ),
    tianditu_v_nosea: L.tileLayer(tianditu_v_nosea, {
      pane: 'overlayPane',
      zIndex: Config.layerIndex.noSeaIndex,
    }),
  }

  let map = L.map('mapContain', {
    attributionControl: false,
    crs: L.CRS.EPSG3857,
    zoomControl: false,
    zoomSnap: 0.1,
    minZoom: 11,
    maxZoom: 14,
    // 全屏
    fullscreenControl: true,
  }).setView(data.center, data.zoom)
  mapObj.map = map
  Config.AllLayers.tianditu_v.addTo(mapObj.map)
  Config.ToolLayers = L.layerGroup().addTo(mapObj.map)
  const wzCenter = [27.9911, 120.6993]

  // 添加点
  // const wzMarker = L.circleMarker(wzCenter, {
  //   color: '#ff0000',
  //   fillColor: '#ff0000',
  //   fillOpacity: 1,
  //   radius: 8,
  // }).addTo(mapObj.map)
  // // 在旁边添加文字
  // const wzLabel = L.marker(wzCenter, {
  //   icon: L.divIcon({
  //     className: 'wz-label',
  //     html: '温州市',
  //     // 图标大小
  //     iconSize: [50, 20],
  //     // 图标锚点
  //     iconAnchor: [25, -15],
  //   }),
  // }).addTo(mapObj.map)
}

export const addHyLayer = () => {
  let index = 0
  // 使用三种青色系颜色
  let allColor = ['#B8E986', '#50E3C2', '#00BFFF']
  let num = -1
  let hyLayer = L.geoJSON(hyJson, {
    // polygon
    style: function (feature) {
      num++
      return {
        color: allColor[num],
        weight: 1,
        opacity: 1,
        fillColor: allColor[num],
        fillOpacity: 0.15,
      };
    },
    // eachLayer
    onEachFeature: function (feature, layer) {
      layerMap['hy' + (++index)] = layer
      mapObj.allQy.push({
        layer: layer,
        name: 'hy' + (index),
      })
    }
  })
    .addTo(mapObj.map)


  // mapObj.allQy.push(hyLayer)
}

export const addDfLayer = () => {
  let dfLine = []
  dfJson.geometries.forEach(item => {
    item.coordinates.forEach(arr => {
      // let isAdd = dfLine.findIndex(v=>{
      //   return v[0] == arr[0] && v[1] == arr[1]
      // })
      // if(isAdd == -1){
      //   dfLine.push(arr)
      // }
      dfLine.push(arr)

    })
  })

  let dfLayer = L.geoJSON(dfJson, {
    style: function (feature) {
      return {
        color: "#ff0000",
        weight: 7,
        opacity: 0.7,
        fillOpacity: 0,
        zIndex: 1,
      };
    },
    onEachFeature: function (feature, layer) {
      layerMap['df1'] = layer
    }
  }).addTo(mapObj.map)
  mapObj.allQy.push({
    layer: dfLayer,
    name: 'df1',
  })
  // var buffered = turf.buffer(dfJson, 300, {
  //   units: 'meters'
  // });
  // let dfLayer2 = L.geoJSON(buffered, {
  //   style: function (feature) {
  //     return {
  //       color: "#ff0000",
  //       weight: 1,
  //       opacity: 0,
  //       fillOpacity: 0,
  //       zIndex: 1,
  //     };
  //   },
  //   onEachFeature: function (feature, layer) {
  //     layerMap['df1'] = layer
  //   }
  // }).addTo(mapObj.map)

  // let line= turf.lineString(dfLine);
  // var lineBuffer = turf.buffer(line, 300, { units: "meters" });
  // let buffer = L.geoJSON(lineBuffer, {
  //   style: function (feature) {
  //     return {
  //       color: "#ff0000",
  //       weight: 1,
  //       opacity: 0.5,
  //       fillOpacity: 0,
  //       zIndex: 1,
  //     };
  //   },
  //   onEachFeature: function (feature, layer) {
  //     layerMap['df1'] = layer
  //   }

  // }).addTo(mapObj.map);

  // mapObj.allQy.push({
  //   layer: buffer,
  //   name: 'df1',
  // })
}

export const addHxLayer = () => {
  let hxLine = [[], []]
  // 添加蓝色小圆点并在同样位置添加更大的透明圆点
  let hxLayer = L.geoJSON(hxJson, {
    pointToLayer: function (feature, latlng) {
      if (feature.properties.OBJECTID == 119 || feature.properties.OBJECTID == 91) {
        // if(feature.properties.OBJECTID == 119){
        //   layerMap['hx2']=
        // }

        let cm = L.circleMarker(latlng, {
          radius: 6,
          fillColor: "#8b572a",
          color: "#8b572a",
          weight: 1,
          opacity: 1,
          fillOpacity: 1,
        });
        if (feature.properties.OBJECTID == 119) {
          mapObj.allQy.push({
            layer: cm,
            name: 'hx3',
          })
          layerMap['hx3'] = cm
        }
        return cm
      } else if (feature.properties.OBJECTID == 65) {
        return L.circleMarker(latlng, {
          radius: 6,
          fillColor: "#E6A23C",
          color: "#E6A23C",
          weight: 1,
          opacity: 1,
          fillOpacity: 1,
        });
      } else if (feature.properties.OBJECTID >= 84) {
        hxLine[0].push([latlng.lng, latlng.lat])
        return L.circleMarker(latlng, {
          radius: 2,
          fillColor: "#8b572a",
          color: "#8b572a",
          weight: 1,
          opacity: 1,
          fillOpacity: 1,
        });
      }
      hxLine[1].push([latlng.lng, latlng.lat])
      return L.circleMarker(latlng, {
        radius: 2,
        fillColor: "#E6A23C",
        color: "#E6A23C",
        weight: 1,
        opacity: 1,
        fillOpacity: 1,
      });
    },

  }).addTo(mapObj.map)

  var line = turf.lineString(hxLine[0]);
  var line2 = turf.lineString(hxLine[1]);
  var lineBuffer = turf.buffer(line, 500, { units: "meters" });
  var lineBuffer2 = turf.buffer(line2, 500, { units: "meters" });
  let buffer = L.geoJSON(lineBuffer, {
    style: function (feature) {
      return {
        color: "#8b572a",
        weight: 1,
        opacity: 0,
        fillOpacity: 0,
      };
    },
    onEachFeature: function (feature, layer) {
      layerMap['hx1'] = layer
    }

  }).addTo(mapObj.map);

  let buffer2 = L.geoJSON(lineBuffer2, {
    style: function (feature) {
      return {
        color: "#E6A23C",
        weight: 1,
        opacity: 0,
        fillOpacity: 0,
      };
    },
    onEachFeature: function (feature, layer) {
      layerMap['hx2'] = layer
    }

  }).addTo(mapObj.map);

  mapObj.allQy.push({
    layer: buffer,
    name: 'hx1',
  })
  mapObj.allQy.push({
    layer: buffer2,
    name: 'hx2',
  })
}

export const addAllTxt = () => {
  let text = L.divIcon({
    html: `<div class="hx_label"><span>五号码头-霓屿南航线</span></div>`,
    className: 'my-div-icon',
    iconAnchor: [50, -20],
    color: '#fff',
  }),
    hxtxt1 = L.marker([27.856, 120.950], {
      icon: text,
    }).addTo(mapObj.map)

  let text2 = L.divIcon({
    html: `<div class="hx_label1"><span>洞头深门-温州市区航线</span></div>`,
    className: 'my-div-icon',
    iconAnchor: [40, -10],
  }),
    hxtxt2 = L.marker([27.937, 121.012], {
      icon: text2,
    }).addTo(mapObj.map)

  let text3 = L.divIcon({
    html: `<div class="hx_label2"><span>五号码头</span></div>`,
    className: 'my-div-icon',
    iconAnchor: [-10, 15],
  }),
    hxtxt3 = L.marker([27.90410850300003, 120.9392498410001], {
      icon: text3,
    }).addTo(mapObj.map)

  const hxtxt4 = L.marker([27.85336913100008, 121.04620098600003], {
    icon: L.divIcon({
      html: `<div class="hx_label3"><span>霓屿石料场</span></div>`,
      className: 'my-div-icon',
      iconAnchor: [-10, 10],
    }),
  }).addTo(mapObj.map)

  const hxtxt5 = L.marker([27.863707565000027, 121.09135311500006], {
    icon: L.divIcon({
      html: `<div class="hx_label4"><span>深门</span></div>`,
      className: 'my-div-icon',
      iconAnchor: [-10, 10],
    }),
  }).addTo(mapObj.map)

  // mapObj.allQy[2].addLayer(hxtxt1)
  // mapObj.allQy[2].addLayer(hxtxt2)
  // mapObj.allQy[2].addLayer(hxtxt3)
  // mapObj.allQy[2].addLayer(hxtxt4)
  // mapObj.allQy[2].addLayer(hxtxt5)

  mapObj.allQy.push({
    layer: hxtxt1,
    name: 'hx1',
  })
  mapObj.allQy.push({
    layer: hxtxt2,
    name: 'hx2',
  })
  mapObj.allQy.push({
    layer: hxtxt3,
    name: 'hx3',
  })


  const hytxt1 = L.marker([27.909, 120.903], {
    icon: L.divIcon({
      html: `<div class="hy_label"><span>南堤-龙湾海域</span></div>`,
      className: 'my-div-icon',
      iconAnchor: [30, 0],
    }),
  }).addTo(mapObj.map)

  const hytxt2 = L.marker([27.969, 120.978], {
    icon: L.divIcon({
      html: `<div class="hy_label1"><span>北堤-大门海域</span></div>`,
      className: 'my-div-icon',
      iconAnchor: [30, 0],
    }),
  }).addTo(mapObj.map)

  const hytxt3 = L.marker([27.887, 120.990], {
    icon: L.divIcon({
      html: `<div class="hy_label2"><span>西堤-霓屿海域</span></div>`,
      className: 'my-div-icon',
      iconAnchor: [30, -20],
    }),
  }).addTo(mapObj.map)

  // mapObj.allQy[0].addLayer(hytxt1)
  // mapObj.allQy[0].addLayer(hytxt2)
  // mapObj.allQy[0].addLayer(hytxt3)

  mapObj.allQy.push({
    layer: hytxt1,
    name: 'hy1',
  })
  mapObj.allQy.push({
    layer: hytxt2,
    name: 'hy3',
  })
  mapObj.allQy.push({
    layer: hytxt3,
    name: 'hy2',
  })


  mapObj.allTxt.push(hxtxt1)
  mapObj.allTxt.push(hxtxt2)
  mapObj.allTxt.push(hxtxt3)
  mapObj.allTxt.push(hxtxt4)
  mapObj.allTxt.push(hxtxt5)
  mapObj.allTxt.push(hytxt1)
  mapObj.allTxt.push(hytxt2)
  mapObj.allTxt.push(hytxt3)
}

export const clearAllTxt = () => {
  mapObj.allTxt.forEach(item => {
    mapObj.map.removeLayer(item)
  })
  mapObj.allTxt = []
}

export const clearAllQy = () => {
  mapObj.allQy.forEach(item => {
    mapObj.map.removeLayer(item.layer)
  })
  mapObj.allQy = []
}

export const addAllQy = () => {
  addHyLayer()
  addDfLayer()
  addHxLayer()

  // mapObj.allQy.forEach(item => {
  //   item.on('click', (e) => {
  //     console.log(mapObj.allQy);
  //   })
  // })
}


export const addArrow = (data) => {
  let arrowPng = L.marker([data.lat, data.lng], {
    icon: L.icon({
      className: "langxiang",
      iconUrl: arrow,
      iconSize: [10, 35]
    }),
    rotationAngle: data.angle,
    draggable: false,
  }).addTo(mapObj.map)
  mapObj.allArrow.push(arrowPng)
}

export const clearArrow = () => {
  mapObj.allArrow.forEach(item => {
    mapObj.map.removeLayer(item)
  })
  mapObj.allArrow = []
  // mapObj.map.off('zoomend')
}

export const addValue = (data) => {
  let valuePng = L.marker([data.lat, data.lng], {
    icon: L.divIcon({
      className: "value",
      html: `<div class="value_label"><span>${data.value}</span></div>`,
      iconSize: [10, 35]
    }),
    draggable: false,
  }).addTo(mapObj.map)
  mapObj.allValue.push(valuePng)
}

export const clearValue = () => {
  mapObj.allValue.forEach(item => {
    mapObj.map.removeLayer(item)
  })
  mapObj.allValue = []
}


export const clearLine = () => {
  mapObj.currentLine.forEach(item => {
    mapObj.map.removeLayer(item)
  })
  mapObj.currentLine = []
}

export const addnoseaLayer = () => {
  if (!mapObj.map.hasLayer(Config.AllLayers.tianditu_v_nosea)) {
    Config.AllLayers.tianditu_v_nosea.addTo(mapObj.map)
  }
  // if (mapObj.map.hasLayer(Config.AllLayers.tianditu_v)) {
  //   // mapObj.map.removeLayer(Config.AllLayers.tianditu_v)
  // }
}

export const resetLayer = () => {
  // if (mapObj.map.hasLayer(Config.AllLayers.tianditu_v_nosea)) {
  //   mapObj.map.removeLayer(Config.AllLayers.tianditu_v_nosea)
  // }
  // if (!mapObj.map.hasLayer(Config.AllLayers.tianditu_v)) {
  //   Config.AllLayers.tianditu_v.addTo(mapObj.map)
  // }
  mapObj.map.removeLayer(Config.AllLayers.tianditu_v_nosea)
  // Config.AllLayers.tianditu_v_nosea.addTo(mapObj.map)
}

export const removenoseaLayer = (name) => {
  // if (!mapObj.map.hasLayer(Config.AllLayers.tianditu_v)) {
  //   Config.AllLayers.tianditu_v.addTo(mapObj.map)
  // }
  if (mapObj.map.hasLayer(Config.AllLayers.tianditu_v_nosea) && provider.key == 'qt') {
    mapObj.map.removeLayer(Config.AllLayers.tianditu_v_nosea)
  }

  //之后根据需求穿
  // if (mapObj.map.hasLayer(Config.AllLayers.surgeLayer)) {
  //   mapObj.map.removeLayer(Config.AllLayers.surgeLayer)
  // }
  // if (mapObj.map.hasLayer(Config.AllLayers.waveLayer)) {
  //   mapObj.map.removeLayer(Config.AllLayers.waveLayer)
  // }
  // if (mapObj.map.hasLayer(Config.AllLayers.tideLayer)) {
  //   mapObj.map.removeLayer(Config.AllLayers.tideLayer)
  // }
  for (let key of ['surgeLayer', 'waveLayer', 'tideLayer', 'windLayer', 'windParticleLayer', 'currentLayer', 'boundaryLineLayer1']) {
    if (mapObj.map.hasLayer(Config.AllLayers[key])) {
      mapObj.map.removeLayer(Config.AllLayers[key])
    }
  }
}

export const removeOtherLayer = (name) => {
  // if (name == 'surge') {
  //   if (mapObj.map.hasLayer(Config.AllLayers.waveLayer)) {
  //     mapObj.map.removeLayer(Config.AllLayers.waveLayer)
  //   }
  //   if (mapObj.map.hasLayer(Config.AllLayers.tideLayer)) {
  //     mapObj.map.removeLayer(Config.AllLayers.tideLayer)
  //   }
  // } else if (name == 'wave') {
  //   if (mapObj.map.hasLayer(Config.AllLayers.surgeLayer)) {
  //     mapObj.map.removeLayer(Config.AllLayers.surgeLayer)
  //   }
  //   if (mapObj.map.hasLayer(Config.AllLayers.tideLayer)) {
  //     mapObj.map.removeLayer(Config.AllLayers.tideLayer)
  //   }
  // }
  // else if (name == 'tide') {
  //   if (mapObj.map.hasLayer(Config.AllLayers.surgeLayer)) {
  //     mapObj.map.removeLayer(Config.AllLayers.surgeLayer)
  //   }
  //   if (mapObj.map.hasLayer(Config.AllLayers.waveLayer)) {
  //     mapObj.map.removeLayer(Config.AllLayers.waveLayer)
  //   }
  // }

  //增水，海浪，潮汐，风，海流
  for (let key of ['surgeLayer', 'waveLayer', 'tideLayer', 'windLayer', 'currentLayer']) {
    // console.log('key:',key,'name:',name);

    if (key.includes(name)) continue
    if (mapObj.map.hasLayer(Config.AllLayers[key])) {
      mapObj.map.removeLayer(Config.AllLayers[key])
      if (key == 'windLayer') {
        if (mapObj.map.hasLayer(Config.AllLayers.boundaryLineLayer1)) {
          mapObj.map.removeLayer(Config.AllLayers.boundaryLineLayer1)
        }
        if (mapObj.map.hasLayer(Config.AllLayers.windParticleLayer)) {
          mapObj.map.removeLayer(Config.AllLayers.windParticleLayer)
        }
      }
    }
  }

  // for (let key in ['surgeLayer', 'waveLayer', 'tideLayer', 'windLayer']) {
  //   if (key.includes(name)) continue
  //   if (mapObj.map.hasLayer(Config.AllLayers[key])) {
  //     mapObj.map.removeLayer(Config.AllLayers[key])
  //   }
  // }
}

export const clearLayers = () => {
  for (let key in Config.AllLayers) {
    if (Config.AllLayers[key]) {
      mapObj.map.removeLayer(Config.AllLayers[key])
    }
  }
}

// const isFullScreen = ref(false)
// export const fullScreen = () => {
//   isFullScreen.value = !isFullScreen.value
//   nextTick(() => {
//     mapObj.map.invalidateSize()
//   })
//   if (isFullScreen.value) {
//     const keydownHandler = (e) => {
//       if (e.key === 'Escape') {
//         isFullScreen.value = false
//         document.removeEventListener('keydown', keydownHandler)
//       }
//     }
//     document.addEventListener('keydown', keydownHandler);
//   }
// }

export const splitTimePeriod = (timePeriod) => {
  const [startMonth, startDay, startHour, endMonth, endDay, endHour] = timePeriod.match(/\d+/g);
  const startDate = new Date(`2021-${startMonth}-${startDay}T${startHour}:00:00`);
  const endDate = new Date(`2021-${endMonth}-${endDay}T${endHour}:00:00`);
  const result = [];
  for (let d = startDate; d < endDate; d.setHours(d.getHours() + 1)) {
    // result.push(new Date(d));
    let tt = new Date(d)
    let month = tt.getMonth() + 1
    let day = tt.getDay()
    let hour = tt.getHours()
    month = month > 10 ? month : '0' + month
    day = day > 10 ? day : '0' + day
    hour = hour > 10 ? hour : '0' + hour
    result.push(month + '月' + day + '日' + hour + '时');

  }
  return result;
}

export const getUid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0,
      v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

export const formatDate = (numb, format) => {
  const time = new Date(+numb);
  const year = time.getFullYear();
  const month = time.getMonth() + 1;
  const date = time.getDate();
  const hour = time.getHours();
  const minute = time.getMinutes();
  return `${month < 10 ? "0" + month : month}月${date < 10 ? "0" + date : date}日${hour < 10 ? "0" + hour : hour}时`
}

export const initListData = async () => {
  let promiseArr = []
  let tableData = [[], []]
  for (let i = 0; i < 2; i++) {
    let a = queryList().then(res => {
      for (let key in res.data.data) {
        tableData[i].push({
          id: getUid(),
          name: key,
          date: '',
          children: (() => {
            let arr = []
            for (let key2 in res.data.data[key]) {
              arr.push({
                id: getUid(),
                name: key2,
                date: '',
                children: (() => {
                  let arr2 = []
                  res.data.data[key][key2].forEach(item => {
                    arr2.push({
                      id: getUid(),
                      name: item.name,
                      date: formatDate(item.startDate, '-') + '至' + formatDate(item.endDate, '-'),
                    })
                  })
                  return arr2
                })()
              })
            }
            return arr
          })()
        })
      }
    })
    promiseArr.push(a)
  }
  await Promise.all(promiseArr)
  return tableData
}

let chart = null
export const initChartTide = (domName, tideList) => {
  let data = []
  tideList.forEach(item => {
    data.push({
      name: item.time,
      value: [item.time, Number(item.depth).toFixed(2)],
      isTop: item.isTop,
    })
  })


  chart = echarts.init(domName)
  let option = {
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        let str = ''
        params.forEach(item => {
          // 显示时间
          str += item.value[0].split('.')[0] + '<br>'
          str += item.marker + item.seriesName + ': ' + item.value[1] + 'm<br>'
        })
        return str
      }
    },
    legend: {
      // data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      // type: 'category',
      // 时间轴
      type: 'time',
      boundaryGap: false,
      // data: tideList.map(item => item.time.split('.')[0]),
    },
    yAxis: {
      type: 'value'
    },
    // dataZoom: [{
    //   type: 'inside',
    //   start: 0,
    //   end: 100
    // }, {
    //   start: 0,
    //   end: 100,
    // }],
    series: [
      {
        color: '#4A90E2',
        name: '水位',
        type: 'line',
        data: data,
        // data: data.map(item => {
        //   return {
        //     name: item.name,
        //     value: [item.name, Number(item.value[1]).toFixed(2) + 'm'],
        //     isTop: item.isTop,
        //   }
        // }),
        smooth: true,
        symbol: 'emptyCircle',

        symbolSize: (value, item) => {
          if (item.data.isTop == 1) {
            return 8
          } else {
            return 4
          }
        },
      },
    ]
  };
  chart.setOption(option)
}

export const destroyChartTide = () => {
  chart?.dispose()
}

export const drawClose = () => {
  chart?.dispose()
}

export const getTideList = (data) => {
  return axios({
    method: 'get',
    url: url + '/wz/getTideList',
    params: {
      type: data.type,
      station: data.station
    }
  })
}

export const getFbList = (data) => {
  return axios({
    method: 'get',
    url: url + '/wz/getFbList',
    params: data

  })
}

export const testPng = (data) => {
  let wjj = data.time.substring(0, 8);
  let imgName = data.time.substring(8, 10);

  let url1 = ''
  if (data.type == 'wave') {
    url1 = url + `/img/${data.type}/${wjj}/ww3.${imgName}.png`
  } else if (data.type == 'tide') {
    url1 = url + `/img/${data.type}/${wjj}/tide.${imgName}.png`
  }
  return axios({
    method: 'get',
    // url: url + `/img/output/${data.time}/taizh_wz_tp_wave.png`
    url: url1
  })
}

export const getPngListByDay = (data) => {
  let wjj = data.time.substring(0, 8);
  // console.log(data);
  // let type = data.type == 'surge' ? 'tide' : data.type
  let type = data.type
  let dir = data.dir ? data.dir : 'img'

  // let imgName = data.time.substring(8, 10);
  return axios({
    method: 'get',
    params: {
      type: type,
      time: wjj,
      dir: dir
    },
    url: url + '/sm/getPngListByDay',
  })
}

export const preloadPng = (data) => {
  // 2023080103
  // http://localhost:5000/api/img/wind/20230801/wind.01.png
  let arr = []
  data.allPng.forEach(item => {
    let urlTemp = `${url}/img/${data.type}/${item.time.substring(0, 8)}/${data.type}.${item.time.substring(8, 10)}.png`
    arr.push(axios({
      method: 'get',
      url: urlTemp
    }))
  })
  return Promise.all(arr)
}

export const layerData = ref({
  left: 0,
  top: 0
})

const initSanAo = () => {
  L.marker([27.20235058486227, 120.51932012727352], {
    icon: L.icon({
      className: "tideStation111",
      iconUrl: './img/star.png',
      iconSize: [20, 20],
    }),
  }).addTo(mapObj.map)
  // 下方添加文字，中心点
  // L.marker([27.20235058486227, 120.51932012727352], {
  //   icon: L.divIcon({
  //     className: "tideStation111",
  //     html: `<div class="marker-label"><span>三奥</span></div>`,
  //     iconSize: [20, 20],
  //     iconAnchor: [10, -10],
  //   }),
  // }).addTo(mapObj.map)

  L.marker([27.200627970249425, 120.52513326673416], {
    icon: L.icon({
      className: "tideStation111",
      iconUrl: './img/tide.png',
      iconSize: [10, 20],
    }),
  }).addTo(mapObj.map)
  // 下方添加文字
  L.marker([27.200627970249425, 120.52513326673416], {
    icon: L.divIcon({
      className: "tideStation111",
      html: `<div class="marker-label"><span>潮位站</span></div>`,
      iconSize: [20, 20],
      iconAnchor: [15, -10],
    }),
  }).addTo(mapObj.map)

  L.circleMarker([27.164984221472636, 120.48114851673497], {
    color: '#4A90E2',
    fillColor: '#4A90E2',
    fillOpacity: 0.5,
    radius: 12,
    pane: 'markerPane',
  }).addTo(mapObj.map)

  L.marker([27.164984221472636, 120.48114851673497], {
    icon: L.divIcon({
      className: "tideStation111",
      html: `<div class="marker-label"><span>霞关</span></div>`,
      iconSize: [20, 20],
      iconAnchor: [12, -15],
    }),
  }).addTo(mapObj.map)

  L.circleMarker([27.229088495762262, 120.54100096954002], {
    // 深蓝色边和浅蓝色填充
    color: '#4A90E2',
    fillColor: '#4A90E2',
    fillOpacity: 0.5,
    radius: 12,
    pane: 'markerPane',
  }).addTo(mapObj.map)

  L.marker([27.229088495762262, 120.54100096954002], {
    icon: L.divIcon({
      className: "tideStation111",
      html: `<div class="marker-label"><span>渔寮</span></div>`,
      iconSize: [20, 20],
      iconAnchor: [12, -15],
    }),
  }).addTo(mapObj.map)

  L.circle([27.20235058486227, 120.51932012727352], {
    color: '#4a90e2',
    // fillColor: '#4A90E2',
    fillOpacity: 0.2,
    radius: 15000,
    weight: 1,
  }).addTo(mapObj.map)
  // 画一个半径为5km的圆
  L.circle([27.20235058486227, 120.51932012727352], {
    color: '#d0021b',
    fillOpacity: 0,
    radius: 5000,
    // 线宽
    weight: 1,
  }).addTo(mapObj.map)


  // 添加5km标识
  L.marker([27.203404926897306, 120.5634527748743], {
    icon: L.divIcon({
      className: "tideStation111",
      html: `<div class="marker-label"><span>5km</span></div>`,
      iconSize: [20, 20],
      iconAnchor: [12, -15],
    }),
  }).addTo(mapObj.map)
  L.marker([27.19646240557804, 120.61091733688577], {
    icon: L.divIcon({
      className: "tideStation111",
      html: `<div class="marker-label"><span>10km</span></div>`,
      iconSize: [20, 20],
      iconAnchor: [12, -15],
    }),
  }).addTo(mapObj.map)
  L.marker([27.192296685281608, 120.6623818343339], {
    icon: L.divIcon({
      className: "tideStation111",
      html: `<div class="marker-label"><span>15km</span></div>`,
      iconSize: [20, 20],
      iconAnchor: [12, -15],
    }),
  }).addTo(mapObj.map)

  L.circle([27.20235058486227, 120.51932012727352], {
    color: '#f8e71c',
    fillOpacity: 0,
    radius: 10000,
    weight: 1,
  }).addTo(mapObj.map)

  // 经度：120.6200 E
  // 纬度：27.2019 N

  // 添加浮标点
  let marker1 = L.marker([27.2019, 120.6200], {
    icon: L.icon({
      className: "fubiao",
      iconUrl: './img/sanjiao.png',
      iconSize: [15, 15],
    })
  }).addTo(mapObj.map)
  // 浮标文字
  L.marker([27.2019, 120.6200], {
    icon: L.divIcon({
      className: "tideStation111",
      html: `<div class="marker-label"><span>浮标</span></div>`,
      iconSize: [20, 20],
      iconAnchor: [12, -15],
    }),
  }).addTo(mapObj.map)
  marker1.on('click', () => {
    mitt.emit('fubiaoClick')
  })
}